<?php
class TaskModel extends Model {
	public $list;
    public function _list($view,$map,$pagesize=20) {
		//计算总页数
		$count = $this->where($map)->count();
		import('ORG.Util.Page');
		//实例化分页类
		$p = new Page($count, $pagesize);
		$list = $this->where($map)->limit($p->firstRow . ',' . $p->listRows)->select();
		$pages = $p->show();
		$_GET['list']=$list;
		$view->assign('list',$list);
		$view->assign('pages',$pages);
    }
	public function filter($view){
        //筛选开始时间与结束时间
        if(trim($_REQUEST['starttime'])!=''){
            $map['time']=array('GT',strtotime($_REQUEST['starttime']));
        }
        if(trim($_REQUEST['endtime'])!=''){
            $map['time']=array('LT',strtotime($_REQUEST['endtime']));
        }
        if(""==trim($_REQUEST['starttime'])&&""==trim($_REQUEST['endtime'])){
            $map['time']=array('GT',strtotime("-1 month"));
        }
        if(""!=trim($_REQUEST['starttime'])&&""!=trim($_REQUEST['endtime'])){
            $map['time']=array('between',array(strtotime($_REQUEST['starttime']),strtotime($_REQUEST['endtime'])));
        }
        //筛选某个职员 或一整个部门
        if(""!=trim($_REQUEST['member_id'])){
            $map['member_id']=$_REQUEST['member_id'];    
        }
		
		//筛选父类
		if(''!=trim($_REQUEST['pid'])){
			$map['pid']=$_REQUEST['pid'];
		}else{
			$map['pid']=0;	
		}
		
        $map['site_id']=__SITEID__;
		
		$this->_list($view,$map);
	}
	
	
	
	public function updateprogress(){//存在任务时更新任务进度
	     $task = $this->find();
		 $mdb = D('Mission');
		 $missioncount = (int)$mdb->where(array('task_id' => $task['id'])) -> count();
		 $complite = $mdb->where(array('task_id' => $task['id'], 'state' => 3)) -> count();
		 if($missioncount > 0){
			 $progress = round($complite/$missioncount * 100, 2);
		 }
		// dump($complite.'/'.$missioncount);
		 $this -> where(array('id' => $task['id'])) -> data(array('progress' => $progress, 'progresstime' => time())) -> save();
		 
	}
	//更新一个任务的分数
	public function SetEventIntegral($ar1, $type = 'add'){
		$integralsum = $this->find();
		$task_id = $integralsum['id'];
		if($task_id == 0){
			$this->error = '不存在任务！';
			return false;
		}
		$missionDB = M('Mission');
		//$this->where(array('id' => $integralsum['id']))->save(array('integralsum' => ''));
		$mission = $missionDB -> where(array('site_id' => __SITEID__, 'task_id' => $task_id)) -> select();
		$ar2 = unserialize($integralsum['integralNum']);
		$ar2 = [$integralsum['member_id']=>['name'=>$integralsum['member_name'],'integral'=>$ar2]];
		foreach($mission as $m){
			$ar1 = $m['integralret']; 
			$ar1 = unserialize($ar1);
			$ar1keys = array_keys($ar1);
			foreach($ar1keys as $k => $v){
			//dump($ar1[$v]['integral']);
				foreach($ar1[$v]['integral'] as $key => $val){
					/*if($type == 'add'){*/
						$ar2[$v]['name'] = $ar1[$v]['name'];
						$ar2[$v]['integral'][$key] += $val;
					/*}else{
						$ar2[$v]['name'] = $ar1[$v]['name'];
						$ar2[$v]['integral'][$key] -= $val;
					}*/
					
				}
			}
		}
		$this->where(array('id' => $integralsum['id']))->save(array('integralsum' => serialize($ar2)));
		return true;
	}
	//时间参数的筛选
	public function timeFilter($time){
		if($time){
			$time=$time>0?'+'.$time:$time;
			if($time == 'month'){	//本月
				$start=strtotime(date('Y')."-".date('m')."-1");//month start unixtime 2016-10-01 00:00:00
				if(date('m')==12){
					$end=strtotime(intval(date('Y')+1)."-1-1");//Jan. 1th for next year
				}else{
					$end=strtotime(date('Y').'-'.intval(date('m')+1).'-1');//1th for next month
				}
				$map=' ( (datetime <='.$end.'  and realtime >= '.$end.') or  (datetime >= '.$start.'  and realtime <= '.$start.') or  (datetime <= '.$start.'  and realtime >='.$end.') or (datetime >= '.$start.'  and realtime <='.$end.') )';
			}elseif($time=='week'){	//本周
				//由于国外一周的第一天是周日，现判断如为周日，开始时间为‘上周一’
				if(date('w')==0){$start=strtotime('last Monday');}
				else{$start=strtotime('Monday this week');}
				$end=$start+7*24*3600;
				$map=' ( (datetime <='.$end.'  and realtime >= '.$end.') or (datetime >= '.$start.'  and realtime <= '.$start.') or  (datetime <= '.$start.'  and realtime >='.$end.') or (datetime >= '.$start.'  and realtime <='.$end.') )';
			}else{					//数值时间
				$then=strtotime($time." days");//那天此时
				$start=mktime(0,0,0,date('m',$then),date('d',$then),date('Y',$then));
				$end=mktime(23,59,59,date('m',$then),date('d',$then),date('Y',$then));
				$map=' datetime <='.$end.' and realtime >='.$start;
			}
		}else{
			$then=time();
			$start=mktime(0,0,0,date('m',$then),date('d',$then),date('Y',$then));
			$end=mktime(23,59,59,date('m',$then),date('d',$then),date('Y',$then));
			$map=' datetime <='.$end.' and realtime >='.$start;
		}
		return $map;
	}
	//各种参数的筛选
	public function parmFilter($status,$type,$important,$belong){
		$missionDB=M('Mission');
		//$sample= 't.site_id ='.__SITEID__.' and realtime between '.$start.' and '.$end.' and temptask = 0';
		$memberId=session(C('USER_AUTH_KEY'));
		$sample= 't.progress <> 100 and t.site_id ='.__SITEID__.' and temptask = 0';
		if(isset($_GET['status'])&&$status==='0'){//状态
			$sample.=' and status = '.$status;
			$sample.=" and ( t.reviewer_id =".$memberId.' or t.member_id = '.$memberId.')';
		}elseif($type){//类型
			$sample.= ' and type_id ='.$type;
			$sample.=" and ( t.reviewer_id =".$memberId.' or t.member_id = '.$memberId.')';
		}elseif($important){//重要程度
			$sample.=' and materiality = '.$important; //1234 轻缓重急
			$sample.=" and ( t.reviewer_id =".$memberId.' or t.member_id = '.$memberId.')';
		}elseif($belong){
			if($belong=='1'){//由我执行
				$sample.=' and t.reviewer_id = '.$memberId;
			}elseif($belong=='2'){//由我发布
				$sample.=' and t.member_id = '.$memberId;
			}elseif($belong=='3'){//由我发布
				$sample.=' and t.creator_id = '.$memberId;
			}
		}else{
			//默认两种情况都显示（跟进人是我，或者发布人是我）或者任务下面的工作有当前用户
			$missionID=$missionDB->where(['member_id'=>$memberId])->group('task_id')->getField('task_id',true);
			$missionID[] = 0;
			$sample.=" and (( t.reviewer_id =".$memberId.' or t.member_id = '.$memberId.' or t.creator_id = '.$memberId.') or (id in('.implode(',',$missionID).')))';
		}
		return $sample;
	}
	
  /*  public function TaskMulti($html)
    {
      
        
        foreach ($html as $key => $val) {
            
            switch ($val['f_type']) {
                
                case '1':
                    {
                        $html[$key]['f_type'] = "text";
                        continue;
                    }
                case '2':
                    {
                        $html[$key]['f_type'] = "file";
                        continue;
                    }
                case '3':
                    {
                   
                        foreach (unserialize($val['valueList']) as $v) {
							
                            $type = 'radio';
                            $checked = '';
                            if ($data == $v['val']) {
                                $checked = ' checked="checked"';
                            }
							
							
                            $inputs .= ':<label class="radio" style="display:inline-block; margin-bottom:5px; margin-right:15px;"><input id="' . $val['f_id'] . '" value="' . $v['lebal'] . '" name="' . $v['val'] . '[]"' . $checked . ' type="' . $type . '" ' . $verifystr . ' /><span>' . $v['lebal'] . '</span></label>';
                        }
                        $html[$key] = $val['name'].$inputs;
                        continue;
                    }
                case '4':
                    {
                        $type = 'checkbox';
                        $i = 0;
                        foreach (unserialize($val['valueList']) as $v) {
                            $checked = '';
                            if ($data == $v['val']) {
                                $checked = ' checked="checked"';
                            }
                            
                            $inputs .= '<label class="radio" style="display:inline-block; margin-bottom:5px; margin-right:15px;"><input id="' . $v['val'] . '" value="' . $v['val'] . '" name="' . $type . '[]"' . $checked . ' type="' . $type . '" ' . $verifystr . ' /><span>' . $v['lebal'] . '</span></label>';
                            $i ++;
                        }
                        continue;
                    }
                case '5':
                    {
                        $html[$key]['f_type'] = "textarea";
                        continue;
                    }
                case '6':
                    {
                        $html[$key]['f_type'] = "img";
                        continue;
                    }
                case '7':
                    {
                        $html[$key]['f_type'] = "submit";
                        continue;
                    }
				case '8':
				    {
						
						$inputs = '<input style="width:100%; cursor:pointer;" readonly value="'.$val['name'].'" class="scrollerinput decorate form-control datetimeinput" placeholder="'.$val['name'].'" id="WdatePicker'.$val['id'].'" name="'.$val[fname].'" type="'.$type.'" '.$verifystr.' onclick="WdatePicker();" />';               
						 $html[$key] = $inputs;
                        continue; 
					}
            }
			
			
        }
     
        return $html;
    }
	

		//一个转换数组表单转换，text方法，需要配合TaskMuil转换出来的Html使用
		  public function transition($html, $data)
    {
            for ($i = 0; $i < count($data); $i ++) {
                $dkey = array();
                $dkey = array_keys($data);
			
                if ($html[$i]['name'] != null) {
				
                    $text[]=$this->toText($html[$i]['name'],$data[$dkey[$i]]);
                }
            }
	
        return $text;
    }
         public function toText($html, $data)
    {
        return  $html . ":" . $data ."\n\r";
    }*/
}